package com.afd.ozblip.activity;

import java.util.Random;

import com.afd.ozblip.util.StringUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.Window;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class BusinessMapActivity extends FragmentActivity implements
		OnMarkerClickListener, OnInfoWindowClickListener {

	//https://code.google.com/apis/console/?noredirect&pli=1#project:823666889354
	/****************** 视图变量 **************************/
	private LinearLayout commonLeftLayout;
	private GoogleMap mMap;

	private TextView topTitleTv;
	/****************** 数据变量 **************************/
	private String businessName;
	private LatLng latLngInfo;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.business_map);
		// 寻找视图
		findViews();
		// 设置监听
		setListeners();
		// 获取参数
		getBundle();
		// 初始化视图
		initViews();
	}

	/**
	 * 寻找视图
	 */
	public void findViews() {
		this.commonLeftLayout = (LinearLayout) findViewById(R.id.ll_common_left);
		this.topTitleTv = (TextView) findViewById(R.id.tv_business_map_topTitle);
	}

	/**
	 * 设置监听
	 */
	public void setListeners() {
		View.OnClickListener mapClick = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.ll_common_left:
					finish();
					break;

				default:
					break;
				}
			}
		};
		this.commonLeftLayout.setOnClickListener(mapClick);
	}

	/**
	 * 获取传递的参数
	 */
	private void getBundle() {
		Intent intent = getIntent();
		businessName = intent.getStringExtra("businessName");
		String lat = intent.getStringExtra("latitude");
		String lng = intent.getStringExtra("longitude");
		if (!StringUtil.isNullOrEmpty(lat) && !StringUtil.isNullOrEmpty(lng)) {
			latLngInfo = new LatLng(Double.valueOf(lat), Double.valueOf(lng));
		}
	}

	private void initViews() {
		if (!StringUtil.isNullOrEmpty(businessName)) {
			this.topTitleTv.setText(businessName);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		setUpMapIfNeeded();
	}

	private void setUpMapIfNeeded() {
		// Do a null check to confirm that we have not already instantiated the
		// map.
		if (mMap == null) {
			// Try to obtain the map from the SupportMapFragment.
			mMap = ((SupportMapFragment) getSupportFragmentManager()
					.findFragmentById(R.id.map)).getMap();
			// Check if we were successful in obtaining the map.
			if (mMap != null) {
				setUpMap();
			}
		}
	}

	private void setUpMap() {
		// Hide the zoom controls as the button panel will cover it.
		mMap.getUiSettings().setZoomControlsEnabled(true);

		// Add lots of markers to the map.
		addMarkersToMap();

		// Setting an info window adapter allows us to change the both the
		// contents and look of the
		// info window.
		mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());

		// Set listeners for marker events. See the bottom of this class for
		// their behavior.
		mMap.setOnMarkerClickListener(this);
		mMap.setOnInfoWindowClickListener(this);

		// Pan to see all markers in view.
		// Cannot zoom to bounds until the map has a size.
		final View mapView = getSupportFragmentManager().findFragmentById(
				R.id.map).getView();
		if (mapView.getViewTreeObserver().isAlive()) {
			mapView.getViewTreeObserver().addOnGlobalLayoutListener(
					new OnGlobalLayoutListener() {
						// We use the new method when supported
						@SuppressLint("NewApi")
						// We check which build version we are using.
						@Override
						public void onGlobalLayout() {
							if (latLngInfo != null) {
								com.google.android.gms.maps.model.LatLngBounds.Builder b = new LatLngBounds.Builder();
								b.include(latLngInfo);
								LatLngBounds bounds = b.build();
								mapView.getViewTreeObserver()
										.removeGlobalOnLayoutListener(this);
								mMap.moveCamera(CameraUpdateFactory
										.newLatLngBounds(bounds, 50));
							}
						}
					});
		}
	}

	private void addMarkersToMap() {
		// 此处添加markets
		// Creates a draggable marker. Long press to drag.
		if (latLngInfo != null) {
			// snippet("Population: 4,137,400")
			mMap.addMarker(new MarkerOptions().position(latLngInfo).title(
					businessName));
		}

	}

	private boolean checkReady() {
		if (mMap == null) {
			Toast.makeText(this, R.string.map_not_ready, Toast.LENGTH_SHORT)
					.show();
			return false;
		}
		return true;
	}

	/** Called when the Clear button is clicked. */
	public void onClearMap(View view) {
		if (!checkReady()) {
			return;
		}
		mMap.clear();
	}

	/** Called when the Reset button is clicked. */
	public void onResetMap(View view) {
		if (!checkReady()) {
			return;
		}
		// Clear the map because we don't want duplicates of the markers.
		mMap.clear();
		addMarkersToMap();
	}

	//
	// Marker related listeners.
	//

	@Override
	public boolean onMarkerClick(final Marker marker) {
		marker.setIcon(BitmapDescriptorFactory.defaultMarker(new Random()
				.nextFloat() * 360));
		return false;
	}

	@Override
	public void onInfoWindowClick(Marker marker) {
		// 商家简介点击
		Toast.makeText(getBaseContext(), "Click Info Window",
				Toast.LENGTH_SHORT).show();
	}

	/** Demonstrates customizing the info window and/or its contents. */
	class CustomInfoWindowAdapter implements InfoWindowAdapter {

		// These a both viewgroups containing an ImageView with id "badge" and
		// two TextViews with id
		// "title" and "snippet".
		private final View mWindow;
		private final View mContents;

		CustomInfoWindowAdapter() {
			mWindow = getLayoutInflater().inflate(R.layout.custom_info_window,
					null);
			mContents = getLayoutInflater().inflate(
					R.layout.custom_info_contents, null);
		}

		@Override
		public View getInfoWindow(Marker marker) {
			render(marker, mWindow);
			return mWindow;
		}

		@Override
		public View getInfoContents(Marker marker) {
			render(marker, mContents);
			return mContents;
		}

		private void render(Marker marker, View view) {
			int badge;
			// Use the equals() method on a Marker to check for equals. Do not
			// use ==.
			// Passing 0 to setImageResource will clear the image view.
			badge = 0;
			((ImageView) view.findViewById(R.id.badge)).setImageResource(badge);

			String title = marker.getTitle();
			TextView titleUi = ((TextView) view.findViewById(R.id.title));
			if (title != null) {
				// Spannable string allows us to edit the formatting of the
				// text.
				SpannableString titleText = new SpannableString(title);
				titleText.setSpan(new ForegroundColorSpan(Color.RED), 0,
						titleText.length(), 0);
				titleUi.setText(titleText);
			} else {
				titleUi.setText("");
			}

			String snippet = marker.getSnippet();
			TextView snippetUi = ((TextView) view.findViewById(R.id.snippet));
			if (snippet != null && snippet.length() > 12) {
				SpannableString snippetText = new SpannableString(snippet);
				snippetText.setSpan(new ForegroundColorSpan(Color.MAGENTA), 0,
						10, 0);
				snippetText.setSpan(new ForegroundColorSpan(Color.BLUE), 12,
						snippet.length(), 0);
				snippetUi.setText(snippetText);
			} else {
				snippetUi.setText("");
			}
		}
	}
}